<?php

namespace App\Notifications\Train\TrainOrder;

use App\Facades\Sms;
use App\Models\Train\TrainOrders\TrainOrder;
use App\Trip\Notify\Channel\SmsChannel;
use App\Trip\Notify\Channel\WechatMiniAppChannel;
use App\Trip\Notify\Channel\WechatOfficialChannel;
use App\Trip\Notify\Sms\Messages\Train\WaitingPayNotifyMessage;
use Cache;
use Carbon\Carbon;
use DateTime;
use Exception;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Notification;
use Log;

class WaitingPayNotify extends Notification implements ShouldQueue
{
    use Queueable;

    private TrainOrder $order;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct(TrainOrder $order)
    {
        $this->order = $order;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param mixed $notifiable
     *
     * @return array
     */
    public function via($notifiable)
    {
        return [SmsChannel::class, WechatMiniAppChannel::class, WechatOfficialChannel::class];
    }


    /**
     * 获取短信通知。
     *
     * @param mixed $notifiable
     *
     * @throws Exception
     */
    public function toSms($notifiable)
    {
        // 如果订单已经取消,或者出票中,改签中就不发消息了
        if ($this->order->isCancel() || $this->order->isTicketing() || $this->order->isChanging()) {
            Log::error("待支付通知,状态不符合无法通知:{$this->order->getOrderSn()},state:{$this->order->getOrderState()}");
            return;
        }

        $cache_key = "WaitingPayNotify:sms:{$this->order->getUserId()}";

        if (Cache::has($cache_key)) {
            Cache::increment($cache_key, 1);
        } else {
            Cache::put($cache_key, 1, new DateTime(Carbon::tomorrow()));
        }

        if (Cache::get($cache_key) > 2) {
            Log::error("待支付通知,超出短信通知次数:{$this->order->getOrderSn()}");
            return;
        }

        try {
            $message = new WaitingPayNotifyMessage($this->order);
            Sms::send($this->order->getMobile(), $message);
        } catch (Exception $e) {
            Log::error("待支付通知,短信发送失败:{$e->getMessage()}");
        }

    }


    /**
     * 获取微信小程序通知。
     *
     * @param mixed $notifiable
     *
     */
    public function toWechatMiniApp($notifiable)
    {
        Log::info("我发微信小程序订阅消息了,暂时没有模板消息,{$this->order->getOrderSn()},待支付提醒");
    }

    /**
     * 获取微信公众号通知。
     *
     * @param mixed $notifiable
     *
     */
    public function toWechatOfficial($notifiable)
    {
        Log::info("我发公众号模板消息了,暂时没有模板消息,{$this->order->getOrderSn()},待支付提醒");
    }
}
